package com.hollycrm.ahunicom.sheet.business.logic.hibernate;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import org.apache.struts.upload.FormFile;
import org.springframework.orm.hibernate.HibernateTemplate;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;

import com.hollycrm.springframework.factory.DefaultBeanFactory;
import com.hollycrm.springframework.util.IdentifierGenerator;
import com.hollycrm.unicom.security.AuthToken;
import com.hollycrm.unicom.sheet.Constants;
import com.hollycrm.unicom.sheet.domain.ConfirmSheet;
import com.hollycrm.unicom.sheet.domain.DealSheet;
import com.hollycrm.unicom.sheet.domain.MainSheet;
import com.hollycrm.unicom.sheet.domain.SheetAppu;
import com.hollycrm.unicom.sheet.flow.SheetAction;
import com.hollycrm.unicom.sheet.flowsupport.ActionExecuteLogic;
import com.hollycrm.unicom.sheet.flowsupport.DoOperateContext;

public class HibernateAddAppuLogic extends HibernateDaoSupport implements
		ActionExecuteLogic {
    public HibernateAddAppuLogic() {
    }

    public void execute(AuthToken auththToken,SheetAction action, DoOperateContext context) throws
        Exception {
        HibernateTemplate ht = getHibernateTemplate();
        String formFileName = (String) context.getInputAttr("formFileName");
        String mainSheetFlowNO = null;
        Object sheet = null;
        /* add by yangcm since 09-2-10 */
        boolean result = true;
        /* end */
        SheetAppu appu = (SheetAppu) context.getInputAttr(SheetAppu.class);
        appu.setSavedName(( (IdentifierGenerator) DefaultBeanFactory.
                               getBean("uuidGenerator")).generate());
        appu.setOriginName(formFileName);
        mainSheetFlowNO = updateAppuCount(ht,appu,context);
        /* add by yangcm since 09-2-10 */
        result = writeFile( (FormFile) context.getInputAttr("formFile"), appu.getSavedName(),
        		                  appu.getSheetFlowNO());
        /* end */
        if(result) ht.save(appu);
  //      writeFile( (FormFile) context.getInputAttr("formFile"), appu.getSavedName(),
  //                appu.getSheetFlowNO());
        context.addOutputAttr("dealType","ADD");
        context.addOutputAttr("mainSheetFlowNO", mainSheetFlowNO);
        context.addOutputAttr("operationObject", appu.getSheetFlowNO());
        context.addOutputAttr("originName",appu.getOriginName());
        context.addOutputAttr("savedName",appu.getSavedName());
        context.addOutputAttr("formFile",context.getInputAttr("formFile"));
        context.addOutputAttr("appu",appu);
    }

    private String updateAppuCount(HibernateTemplate ht,SheetAppu appu,DoOperateContext context) throws Exception {
        String flowNO = null;
        if(appu.getSheetType().equals(Constants.SHEET_TYPE_MAIN)){
            MainSheet sheet = (MainSheet)ht.load(MainSheet.class,appu.getSheetFlowNO());
            flowNO = sheet.getSheetFlowNO();
            sheet.setAppuCount(new Integer(sheet.getAppuCount().intValue()+1));
            ht.update(sheet);
            context.addOutputAttr(sheet);
        }else if(appu.getSheetType().equals(Constants.SHEET_TYPE_DEAL)){
        	MainSheet sheet = (MainSheet)ht.load(MainSheet.class,appu.getSheetFlowNO());
            flowNO = sheet.getSheetFlowNO();
        	 /* add by yangcm since 09-2-10 
            DealSheet sheet = (DealSheet)ht.load(DealSheet.class,appu.getSheetFlowNO());
            flowNO = sheet.getMainSheetFlowNO();
            
            sheet.setAppuCount(new Integer(sheet.getAppuCount().intValue()+1));
            ht.update(sheet);
            context.addOutputAttr(sheet.getMainSheet());
            */
            List dealSheetList = ht.find("from dealSheet in " + DealSheet.class + " where dealSheet.mainSheetFlowNO='" + flowNO + "'");
            Iterator it = dealSheetList.iterator();
            while(it.hasNext()) {
            	DealSheet dealSheet = (DealSheet)it.next();
        	    flowNO = dealSheet.getMainSheetFlowNO();
        	    dealSheet.setAppuCount(new Integer(sheet.getAppuCount().intValue()));
        	    ht.update(dealSheet);
            }
        }else if(appu.getSheetType().equals(Constants.SHEET_TYPE_CONFIRM)){
            ConfirmSheet sheet = (ConfirmSheet)ht.load(ConfirmSheet.class,appu.getSheetFlowNO());
            flowNO = sheet.getMainSheetFlowNO();
            sheet.setAppuCount(new Integer(sheet.getAppuCount().intValue()+1));
            ht.update(sheet);
            context.addOutputAttr(sheet.getMainSheet());
        }
        return flowNO;
    }
    
    /**
     * add by yangcm 09-2-10
     * @param file
     * @param savedFileName
     * @param sheetFlowNo
     * @return
     */
    private boolean writeFile(FormFile file,String savedFileName,String sheetFlowNo) throws Exception{
    	boolean bfalge = true;
    	OutputStream out = null;
    	InputStream in = null;
    	try{
    		int isize = file.getFileSize();
System.out.println("-----------writeFile size is:" + isize);
    		in = file.getInputStream();
    		String uploadPath = Constants.getValue("UPLOAD_FILE_PATH");
    		File path = new File(uploadPath + File.separator + sheetFlowNo );
    		if(!path.exists()) path.mkdirs();
    		out = new FileOutputStream(path.getPath() + File.separator + savedFileName);
    		int bytesRead = 0;
    		byte[] buffer = new byte[8192];
    		while((bytesRead=in.read(buffer, 0, 8192)) != -1){
    			out.write(buffer,0,bytesRead);
    		}
    	}catch(IOException e){
    		bfalge = false;
    		e.printStackTrace();
    	}finally{
    		in.close();
    		out.close();
    		file.destroy();
    	}
    	return bfalge;
    }
}
